package org.goodsmanager.controller;

import jakarta.servlet.http.HttpSession;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.goodsmanager.common.Result;
import org.goodsmanager.entity.Product;
import org.goodsmanager.entity.User;
import org.goodsmanager.service.ProductService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Dashboard统计控制器
 *
 * @author Goods Manager System
 * @version 1.0.0
 */
@Slf4j
@Controller
@RequestMapping("/dashboard")
@RequiredArgsConstructor
public class DashboardController {

    private final ProductService productService;

    /**
     * 首页Dashboard
     */
    @GetMapping
    public String index(HttpSession session, Model model) {
        // 检查用户是否已登录
        User currentUser = (User) session.getAttribute("currentUser");
        if (currentUser == null) {
            // 未登录，重定向到登录页面
            return "redirect:/auth/login";
        }
        
        // 将当前用户信息传递到视图
        model.addAttribute("currentUser", currentUser);
        try {
            // 获取统计信息
            Map<String, Object> statistics = new HashMap<>();
            try {
                statistics = productService.getStatistics();
            } catch (Exception e) {
                log.warn("获取统计信息失败: {}", e.getMessage());
            }
            
            // 确保统计数据不为null
            if (statistics == null) {
                statistics = new HashMap<>();
            }
            
            // 设置默认值
            statistics.putIfAbsent("totalProducts", 0);
            statistics.putIfAbsent("totalStock", 0);
            statistics.putIfAbsent("totalSales", 0);
            statistics.putIfAbsent("totalValue", 0.0);
            statistics.putIfAbsent("lowStockCount", 0);

            // 获取热销商品
            List<Product> hotProducts = new ArrayList<>();
            try {
                hotProducts = productService.getHotProducts(5);
            } catch (Exception e) {
                log.warn("获取热销商品失败: {}", e.getMessage());
            }

            // 获取新品
            List<Product> newProducts = new ArrayList<>();
            try {
                newProducts = productService.getNewProducts(5);
            } catch (Exception e) {
                log.warn("获取新品失败: {}", e.getMessage());
            }

            // 获取库存预警
            List<Product> lowStockProducts = new ArrayList<>();
            try {
                lowStockProducts = productService.getLowStockProducts();
            } catch (Exception e) {
                log.warn("获取库存预警商品失败: {}", e.getMessage());
            }

            model.addAttribute("statistics", statistics);
            model.addAttribute("hotProducts", hotProducts != null ? hotProducts : new ArrayList<>());
            model.addAttribute("newProducts", newProducts != null ? newProducts : new ArrayList<>());
            model.addAttribute("lowStockProducts", lowStockProducts != null ? lowStockProducts : new ArrayList<>());

            return "dashboard/index";
        } catch (Exception e) {
            log.error("加载Dashboard失败", e);
            model.addAttribute("error", "加载Dashboard失败: " + e.getMessage());
            return "error";
        }
    }

    /**
     * 获取统计数据API
     */
    @GetMapping("/statistics")
    @ResponseBody
    public Result<Map<String, Object>> getStatistics() {
        try {
            Map<String, Object> statistics = productService.getStatistics();
            return Result.success(statistics);
        } catch (Exception e) {
            log.error("获取统计数据失败", e);
            return Result.error("获取统计数据失败: " + e.getMessage());
        }
    }
}

